import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Radio,
  Space,
  DatePicker,
  Table,
  Tag,
  message,
  Modal,
} from "antd";

import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { delArticleByIdAPI, getArticlesAPI } from "../../api/article";
import { EditOutlined } from "@ant-design/icons";
import Channel from "component/Channel";

import errorSrc from "assets/error.png";
import { useHistory } from "react-router-dom";
const { RangePicker } = DatePicker;

export default function ArticleList() {
  // 1。 创建ref
  const formDataRef = useRef(null);
  const pageInfoRef = useRef(null);
  const articleStatus = [
    { id: -1, name: "全部", color: "magenta" },
    { id: 0, name: "草稿", color: "orange" },
    { id: 1, name: "待审核", color: "red" },
    { id: 2, name: "审核通过", color: "green" },
    { id: 3, name: "审核失败", color: "cyan" },
  ];
  // 声明状态
  const [articleData, setArticleData] = useState([]);

  // 请求文章列表数据
  const loadArticles = async (params) => {
    const res = await getArticlesAPI(params);
    console.log("文章列表", res);
    setArticleData(res.data);
  };

  // 挂载时钩子
  useEffect(() => {
    // 发送请求
    loadArticles();
  }, []);
  // 筛选列表按钮
  const handleSubmit = (values) => {
    let formData = { ...values };
    if (values.status === -1) {
      delete formData.status;
    }

    if (values.date) {
      const startTime = values.date[0]
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      const endTime = values.date[1].endOf("day").format("YYYY-MM-DD HH:mm:ss");
      formData.begin_pubdate = startTime;
      formData.end_pubdate = endTime;
      delete formData.date;
    }

    // 2. .current 分配表单数据
    formDataRef.current = formData;
    console.log("formData  ----->  ", formData);
    loadArticles(formData);
  };
  // 切换页面触发的回调
  const handleChange = (page, pageSize) => {
    // 分页时存入数据
    pageInfoRef.current = { page, per_page: pageSize };
    // 2. 改造调用方式为传对象
    loadArticles({ page, per_page: pageSize });

    //  取ref数据
    console.log("formDataRef", formDataRef);
    // 💥 注意，初始current可能为null的问题
    loadArticles({ page, per_page: pageSize, ...(formDataRef.current || {}) });
  };

  const handleDelById = (id) => {
    // 1. antd找Modal的组件，确认API
    Modal.confirm({
      title: "温馨提示",
      content: "你确定要删除这篇文章？",
      // 2. onOk改为异步函数
      onOk: async () => {
        // 2. 点击删除
        await delArticleByIdAPI(id);
        const formData = formDataRef.current || {};
        // 删除成功后，刷新界面时，传入分页数据
        const pageInfoData = pageInfoRef.current || {};
        // 3. 重新请求刷新界面 🔔 加回查询参数
        loadArticles({ ...formData, ...pageInfoData });
        // 4. 删除成功
        message.success("删除成功", 1);
      },
    });
  };

  const history = useHistory();

  const columns = [
    {
      // 控制表头文字显示
      title: "封面",
      // 从每行数据的某个字段中，取出数据显示在该列
      // 🔔有dataIndex, 可以省略key
      dataIndex: "cover",
      // 指定唯一列
      // key: 'name',
      // render自定义渲染内容
      render: (value) => {
        // console.log("value  ----->  ", value);
        if (!value.images.length) {
          return <img width={100} height={60} src={errorSrc} alt="" />;
        }
        return <img width={100} height={60} src={value.images[0]} alt="" />;
      },
    },
    {
      title: "标题",
      dataIndex: "title",
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (value, record, index) => {
        // console.log(value);
        const info = articleStatus.find((item) => value === item.id);
        return <Tag color={info.color}>{info.name}</Tag>;
      },
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
    },
    {
      title: "操作",
      key: "action",
      render: (value, record, index) => {
        return (
          <Space>
            <Button
              onClick={() => history.push("/edit/" + record.id)}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            />
            <Button type="primary" onClick={() => handleDelById(record.id)}>
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ paddingTop: 24 }}>
      <Card
        bordered={false}
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          initialValues={{ status: -1, channel_id2: 0 }}
          autoComplete="off"
          onFinish={handleSubmit}
        >
          {/* 状态 */}
          <Form.Item name="status" label="状态">
            <Radio.Group>
              <Radio value="-1">全部</Radio>
              <Radio value="0">草稿</Radio>
              <Radio value="1">待审核</Radio>
              <Radio value="2">审核通过</Radio>
              <Radio value="3">审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          {/* 频道 */}

          <Form.Item label="频道" name="channel_id2">
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          {/* 时间选择框 */}
          <Form.Item name="date" label="日期">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        {/* 列表 */}
        根据筛选条件共查询到 {articleData.total_count} 条结果：
        <Table
          // 分页配置
          pagination={{
            current: articleData.page,
            pageSize: articleData.per_page,
            total: articleData.total_count,
            onChange: handleChange,
          }}
          // 控制没行数据
          dataSource={articleData.results}
          // columns控制列显示
          columns={columns}
          //  1. 给Table指定每行的key
          rowKey="id"
        />
      </Card>
    </div>
  );
}
